(* Module servant à l'échantillonnage de l'image pour le moteur 3D *)

let precision = 5

(* Cherche récursivement la hauteur correspondant à la couleur spécifiée *)
(* prend en paramètres une couleur et une liste du record legende *)
let rec find_height col = function
    [] -> invalid_arg "Color not found. Khan_e fail."
  | e::l -> if e.Types.color = col then e.Types.height else
          find_height col l

(* Crée la grille permettant de visualiser l'échantillonnage de l'image pour le moteur 3D *)
let create_grid image_mat =
  let (w,h) = (Array.length image_mat, Array.length image_mat.(0)) in
  for i = 0 to w-1 do
    for j = 0 to h-1 do
      if(j mod precision = 0 || i mod precision = 0) then
	image_mat.(i).(j) <- Graphics.black;
    done;
  done;
    image_mat

(*Crée le tableau de vertex à partir de l'image à echantillonner *)
(* Prend en paramètres la matrice de l'image à échantillonner et un liste du record legend *)

let rec horror image_mat i j height_list =
  if image_mat.(i).(j) = Graphics.black then horror image_mat (i+1) j height_list else
    find_height image_mat.(i).(j) height_list 


let create_vertices image_mat height_list =
  let (w,h) = (Array.length image_mat, Array.length image_mat.(0)) in
  let vertmat = Array.make_matrix (w/precision+1) (h/precision+1) {Types.x=0.; Types.y=0.; Types.z=0.} in
    for i = 0 to w-1 do
      for j = 0 to h-1 do
	if(j mod precision = 0 && i mod precision = 0) then
	  begin
	  if not(image_mat.(i).(j) = Graphics.black) then
	  vertmat.(i/precision).(j/precision) <- {Types.x=float_of_int i; Types.y=float_of_int j; Types.z=float_of_int(find_height image_mat.(i).(j) height_list)}
	  else
	    failwith "BLAAAACK";
	  end 
      done;
    done;
    vertmat


let triangulation vertices_mat =
  let (w,h) = (Array.length vertices_mat, Array.length vertices_mat.(0)) in
  let triangle_tab = Array.make ((w-1)*(h-1)*2) 
    {Types.p1=vertices_mat.(0).(0); Types.p2=vertices_mat.(0).(1); Types.p3=vertices_mat.(1).(0);
     Types.norm={Types.x=0.;Types.y=0.;Types.z=0.}} in
  let k = ref 0 in
    for i=0 to w-2 do
      for j=0 to h-2 do
	triangle_tab.(!k) <- {Types.p1=vertices_mat.(i).(j); Types.p2=vertices_mat.(i).(j+1);
			    Types.p3=vertices_mat.(i+1).(j); Types.norm={Types.x=0.0;Types.y=0.0;z=1.0}};
	triangle_tab.(!k+1) <- {Types.p1=vertices_mat.(i+1).(j); Types.p2=vertices_mat.(i).(j+1);
			       Types.p3=vertices_mat.(i+1).(j+1); Types.norm={Types.x=0.0;Types.y=0.0;Types.z=1.0}};
	k := !k+2
      done;
    done;
    triangle_tab

(*EOF*)

